﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Security.Cryptography;
using System.Net;
using System.Text.RegularExpressions;
using System.Net.Security;
using System.IO;

namespace JJ.COMMON
{
    
    public static class BaiDuAPI
    {
        #region 配置信息
        //快盘API申请地址http://www.kuaipan.cn/developers
        static string consumer_key = "xc3MeEela0FIL6kf";//快盘申请的key
        static string consumer_secret = "CLnytgfzM1FIfrVH";//开发者srcret
        public static string UserName = "yang0000meng@qq.com";//模拟授权所使用用户邮箱，一定要记得把账号添加到测试账号列表，不然无法使用！
        static string PassWord = "yang2266452";//模拟授权所使用用户对应的密码
        static int MaxError = 3;//当出现错误时尝试重新执行的最大次数；
        #endregion

        /// <summary>
        /// 上传文件，成功返回200，失败返回500
        /// </summary>
        /// <param name="FilePath">本地文件夹路径</param>
        /// <param name="ToFilePath">远程文件路径</param>
        /// <returns></returns>
        public static int UpFile(string FilePath, string ToFilePath)
        {
            int Error = 0;
            ToFilePath = ToFilePath.Replace(" ", "");
            AVAVAV:
            try
            {
                ToFilePath = UrlEncode(ToFilePath, Encoding.UTF8);
                string ReturnData;
                GET_HTTP("http://api-content.dfs.kuaipan.cn/1/fileops/upload_locate", "http://api-content.dfs.kuaipan.cn/1/fileops/upload_locate", "", "", false, new System.Net.CookieContainer(), false, out ReturnData);
                Dictionary<string, object> Dic = JsonToDictionary.ToDictionary(ReturnData);
                if (Dic["stat"].ToString() == "OK")
                {
                    Dictionary<string, object> Dic_oauth = requestToken();
                    Dic_oauth = accessToken(Dic_oauth["oauth_token"].ToString(), Dic_oauth["oauth_token_secret"].ToString());
                    string Url = Dic["url"].ToString() + "1/fileops/upload_file";

                    string oauth_nonce = new Random().NextDouble().ToString().Substring(2, 13);
                    oauth_nonce += oauth_nonce;
                    string NowUnixTime = ConvertDateTimeInt(DateTime.Now).ToString();

                    Dictionary<string, string> Argument = new Dictionary<string, string>();
                    Argument.Add("oauth_nonce", oauth_nonce);
                    Argument.Add("oauth_timestamp", NowUnixTime);
                    Argument.Add("oauth_consumer_key", consumer_key);
                    Argument.Add("oauth_token", Dic_oauth["oauth_token"].ToString());
                    Argument.Add("overwrite", "true");
                    Argument.Add("path", ToFilePath);
                    Argument.Add("root", "app_folder");
                    string Sign = OAuthSign("post", Url, Argument, consumer_secret + "&" + Dic_oauth["oauth_token_secret"].ToString());

                    Url += string.Format("?oauth_signature={0}&oauth_consumer_key={1}&oauth_nonce={2}&oauth_timestamp={3}&oauth_token={4}&overwrite=true&path={5}&root=app_folder", Sign, consumer_key, oauth_nonce, NowUnixTime, Dic_oauth["oauth_token"].ToString(), ToFilePath);

                    CNNWebClient WebC = new CNNWebClient();
                    WebC.UploadFile(Url, FilePath);
                    return 200;
                }
                else
                {
                    return 500;
                }
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.ToString());
                Error++;
                if (Error > MaxError) return 500;
                else goto AVAVAV;
            }
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="Path">文件夹路径</param>
        /// <returns></returns>
        public static int Create_Folder(string Path)
        {
            Path = Path.Replace(" ", "");
            Path = UrlEncode(Path, Encoding.UTF8);
            int Error = 0;
        AVAVAV:
            try
            {
                string oauth_token, oauth_token_secret;
                string FilePath = System.Web.HttpContext.Current.Server.MapPath("/");
                Dictionary<string, object> Dic_oauth = new Dictionary<string, object>();
                System.IO.FileInfo F = new FileInfo(FilePath + "\\KuaiPanAPI.config");
                if (F.Exists && ConvertDateTimeInt(DateTime.Now) - ConvertDateTimeInt(F.LastWriteTime) < 2629743)
                {
                    string Data = System.IO.File.ReadAllText(FilePath + "\\KuaiPanAPI.config");
                    oauth_token = GetString(Data, "oauth_token");
                    oauth_token_secret = GetString(Data, "oauth_token_secret");
                }
                else
                {
                    if (F.Exists) F.Delete();
                    Dic_oauth = requestToken();
                    Dic_oauth = accessToken(Dic_oauth["oauth_token"].ToString(), Dic_oauth["oauth_token_secret"].ToString());
                    oauth_token = Dic_oauth["oauth_token"].ToString();
                    oauth_token_secret = Dic_oauth["oauth_token_secret"].ToString();
                }
                string Url = "http://openapi.kuaipan.cn/1/fileops/create_folder";

                string oauth_nonce = new Random().NextDouble().ToString().Substring(2, 13);
                oauth_nonce += oauth_nonce;
                string NowUnixTime = ConvertDateTimeInt(DateTime.Now).ToString();

                Dictionary<string, string> Argument = new Dictionary<string, string>();
                Argument.Add("oauth_nonce", oauth_nonce);
                Argument.Add("oauth_timestamp", NowUnixTime);
                Argument.Add("oauth_consumer_key", consumer_key);
                Argument.Add("oauth_token", oauth_token);
                Argument.Add("path", Path);
                Argument.Add("root", "app_folder");
                string Sign = OAuthSign("GET", Url, Argument, consumer_secret + "&" + oauth_token_secret);

                Url = string.Format("http://openapi.kuaipan.cn/1/fileops/create_folder?oauth_signature={0}&oauth_consumer_key={1}&oauth_nonce={2}&oauth_timestamp={3}&oauth_token={4}&path={5}&root=app_folder", Sign, consumer_key, oauth_nonce, NowUnixTime, oauth_token, Path);

                string ReturnData;
                GET_HTTP(Url, Url, "", "", false, new System.Net.CookieContainer(), false, out ReturnData);
                if (ReturnData != "")
                {
                    File.WriteAllText(FilePath + "\\KuaiPanAPI.config", string.Format("oauth_token[{0}]oauth_token_secret[{1}]", oauth_token, oauth_token_secret), Encoding.UTF8);
                    return 200;
                }
                else return 500;
            }
            catch
            {
                Error++;
                if (Error > MaxError) return 500;
                else goto AVAVAV;
            }
        }

        /// <summary>
        /// 下载文件到本地
        /// </summary>
        /// <param name="Path">远程路径</param>
        /// <param name="ToFilePath">本地路径</param>
        /// <returns></returns>
        public static int DownFile(string Path,string ToFilePath)
        {
            Path = Path.Replace(" ", "");
            Path = UrlEncode(Path, Encoding.UTF8);
            int Error = 0;
        AVAVAV:
            try
            {
                Dictionary<string, object> Dic_oauth = requestToken();
                Dic_oauth = accessToken(Dic_oauth["oauth_token"].ToString(), Dic_oauth["oauth_token_secret"].ToString());
                string Url = "http://api-content.dfs.kuaipan.cn/1/fileops/download_file";

                string oauth_nonce = new Random().NextDouble().ToString().Substring(2, 13);
                oauth_nonce += oauth_nonce;
                string NowUnixTime = ConvertDateTimeInt(DateTime.Now).ToString();

                Dictionary<string, string> Argument = new Dictionary<string, string>();
                Argument.Add("oauth_nonce", oauth_nonce);
                Argument.Add("oauth_timestamp", NowUnixTime);
                Argument.Add("oauth_consumer_key", consumer_key);
                Argument.Add("oauth_token", Dic_oauth["oauth_token"].ToString());
                Argument.Add("path", Path);
                Argument.Add("root", "app_folder");
                string Sign = OAuthSign("GET", Url, Argument, consumer_secret + "&" + Dic_oauth["oauth_token_secret"].ToString());

                Url = string.Format("http://api-content.dfs.kuaipan.cn/1/fileops/download_file?oauth_signature={0}&oauth_consumer_key={1}&oauth_nonce={2}&oauth_timestamp={3}&oauth_token={4}&path={5}&root=app_folder", Sign, consumer_key, oauth_nonce, NowUnixTime, Dic_oauth["oauth_token"].ToString(), Path);


                HttpWebRequest req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(Url));
                req.Method = "HEAD";
                req.AllowAutoRedirect = false;
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();

                string ToUrl, Cookie;
                Cookie = res.Headers["Set-Cookie"];
                ToUrl = res.Headers["Location"];
                res.Close();
                req.Abort();

                System.Net.WebClient WebC = new System.Net.WebClient();
                WebC.Headers.Add("Cookie", Cookie);
                WebC.DownloadFile(ToUrl, ToFilePath);
                return 200;
            }
            catch
            {
                Error++;
                if (Error > MaxError) return 500;
                else goto AVAVAV;
            }
        }

        /// <summary>
        /// 获取下载链接
        /// </summary>
        /// <param name="Path">远程路径</param>
        /// <returns></returns>
        public static string GetDownFile(string Path)
        {
            Path = Path.Replace(" ", "");
            Path = UrlEncode(Path, Encoding.UTF8);
            int Error = 0;
        AVAVAV:
            try
            {
                string oauth_token, oauth_token_secret;
                string FilePath = CMN.Common.Utils.GetServerPath();// System.Web.HttpContext.Current.Server.MapPath("/");
                Dictionary<string, object> Dic_oauth = new Dictionary<string, object>();
                System.IO.FileInfo F = new FileInfo(FilePath + "\\KuaiPanAPI.config");
                if (F.Exists && ConvertDateTimeInt(DateTime.Now) - ConvertDateTimeInt(F.LastWriteTime) < 2629743)
                {
                    string Data = System.IO.File.ReadAllText(FilePath + "\\KuaiPanAPI.config");
                    oauth_token = GetString(Data, "oauth_token");
                    oauth_token_secret = GetString(Data, "oauth_token_secret");
                }
                else
                {
                    if (F.Exists) F.Delete();
                    Dic_oauth = requestToken();
                    Dic_oauth = accessToken(Dic_oauth["oauth_token"].ToString(), Dic_oauth["oauth_token_secret"].ToString());
                    oauth_token = Dic_oauth["oauth_token"].ToString();
                    oauth_token_secret = Dic_oauth["oauth_token_secret"].ToString();
                }
                string Url = "http://api-content.dfs.kuaipan.cn/1/fileops/download_file";

                string oauth_nonce = new Random().NextDouble().ToString().Substring(2, 13);
                oauth_nonce += oauth_nonce;
                string NowUnixTime = ConvertDateTimeInt(DateTime.Now).ToString();

                Dictionary<string, string> Argument = new Dictionary<string, string>();
                Argument.Add("oauth_nonce", oauth_nonce);
                Argument.Add("oauth_timestamp", NowUnixTime);
                Argument.Add("oauth_consumer_key", consumer_key);
                Argument.Add("oauth_token", oauth_token);
                Argument.Add("path", Path);
                Argument.Add("root", "app_folder");
                string Sign = OAuthSign("GET", Url, Argument, consumer_secret + "&" + oauth_token_secret);

                Url = string.Format("http://api-content.dfs.kuaipan.cn/1/fileops/download_file?oauth_signature={0}&oauth_consumer_key={1}&oauth_nonce={2}&oauth_timestamp={3}&oauth_token={4}&path={5}&root=app_folder", Sign, consumer_key, oauth_nonce, NowUnixTime, oauth_token, Path);
                File.WriteAllText(FilePath + "\\KuaiPanAPI.config", string.Format("oauth_token[{0}]oauth_token_secret[{1}]", oauth_token, oauth_token_secret), Encoding.UTF8);
                return Url;
            }
            catch(Exception ex)
            {
                Error++;
                if (Error > MaxError) return "/500";
                else goto AVAVAV;
            }
        }

        /// <summary>
        /// 获取网盘分享链接地址
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static string GetDownUrl(string Path)
        {
            Path = Path.Replace(" ", "");
            Path = UrlEncode(Path, Encoding.UTF8);
            int Error = 0;
        AVAVAV:
            try
            {
                string oauth_token, oauth_token_secret;
                string FilePath =CMN.Common.Utils.GetServerPath();// System.Web.HttpContext.Current.Server.MapPath("/");
                Dictionary<string, object> Dic_oauth = new Dictionary<string, object>();
                System.IO.FileInfo F = new FileInfo(FilePath + "\\KuaiPanAPI.config");
                if (F.Exists && ConvertDateTimeInt(DateTime.Now) - ConvertDateTimeInt(F.LastWriteTime) < 2629743)
                {
                    string Data = System.IO.File.ReadAllText(FilePath + "\\KuaiPanAPI.config");
                    oauth_token = GetString(Data, "oauth_token");
                    oauth_token_secret = GetString(Data, "oauth_token_secret");
                }
                else
                {
                    if (F.Exists) F.Delete();
                    Dic_oauth = requestToken();
                    Dic_oauth = accessToken(Dic_oauth["oauth_token"].ToString(), Dic_oauth["oauth_token_secret"].ToString());
                    oauth_token = Dic_oauth["oauth_token"].ToString();
                    oauth_token_secret = Dic_oauth["oauth_token_secret"].ToString();
                }
                string Url = "http://openapi.kuaipan.cn/1/shares/app_folder/"+Path;

                string oauth_nonce = new Random().NextDouble().ToString().Substring(2, 13);
                oauth_nonce += oauth_nonce;
                string NowUnixTime = ConvertDateTimeInt(DateTime.Now).ToString();

                Dictionary<string, string> Argument = new Dictionary<string, string>();
                Argument.Add("oauth_nonce", oauth_nonce);
                Argument.Add("oauth_timestamp", NowUnixTime);
                Argument.Add("oauth_consumer_key", consumer_key);
                Argument.Add("oauth_token", oauth_token);
                Argument.Add("path", Path);
                Argument.Add("root", "app_folder");
                string Sign = OAuthSign("GET", Url, Argument, consumer_secret + "&" + oauth_token_secret);

                Url = string.Format("http://openapi.kuaipan.cn/1/shares/app_folder/{5}?oauth_signature={0}&oauth_consumer_key={1}&oauth_nonce={2}&oauth_timestamp={3}&oauth_token={4}", Sign, consumer_key, oauth_nonce, NowUnixTime, oauth_token, Path);
                File.WriteAllText(FilePath + "\\KuaiPanAPI.config", string.Format("oauth_token[{0}]oauth_token_secret[{1}]", oauth_token, oauth_token_secret), Encoding.UTF8);
                return Url;
            }
            catch
            {
                Error++;
                if (Error > MaxError) return "/500";
                else goto AVAVAV;
            }
        }

        /// <summary>
        /// 获取未授权的临时 token
        /// </summary>
        /// <returns></returns>
        static Dictionary<string, object> requestToken()
        {
            try
            {
                string oauth_nonce = new Random().NextDouble().ToString().Substring(2, 13);
                oauth_nonce += oauth_nonce;
                string NowUnixTime = ConvertDateTimeInt(DateTime.Now).ToString();

                Dictionary<string, string> Argument = new Dictionary<string, string>();
                Argument.Add("oauth_nonce", oauth_nonce);
                Argument.Add("oauth_timestamp", NowUnixTime);
                Argument.Add("oauth_consumer_key", consumer_key);
                string Sign = OAuthSign("get", "https://openapi.kuaipan.cn/open/requestToken", Argument, consumer_secret + "&");

                string Url = string.Format("https://openapi.kuaipan.cn/open/requestToken?oauth_consumer_key={2}&oauth_timestamp={1}&oauth_nonce={0}&oauth_signature={3}", oauth_nonce, NowUnixTime, consumer_key, Sign);

                string ReturnData;
                GET_HTTP(Url, Url, "", "", false, new System.Net.CookieContainer(), true, out ReturnData);
                return JsonToDictionary.ToDictionary(ReturnData);
            }
            catch { return null; }
            
        }

        static Dictionary<string, object> accessToken(string Token, string Token_Secret)
        {
            try
            {
                #region 模拟用户授权
                string Str;
                System.Net.CookieContainer C = GET_HTTP("https://www.kuaipan.cn/api.php?ac=open&op=authorise&oauth_token=" + Token, "", "", "", false, new System.Net.CookieContainer(), true, out Str);//获取登录页面基本数据，用于下一步POST

                string S = GetString(Str, "name=\"s\" value=\"", "\"/>", false, 0);
                string App_Name = GetString(Str, "name=\"app_name\" value=\"", "\"/>", false, 0);

                C = POST_SITE_DATA_Cookie("https://www.kuaipan.cn/api.php?ac=open&op=authorisecheck", "https://www.kuaipan.cn/api.php?ac=open&op=authorisecheck", "", "", false, false, C, string.Format("username={3}&userpwd={4}&s={0}&app_name={1}&oauth_token={2}", S, UrlEncode(App_Name, Encoding.UTF8), Token, UrlEncode(UserName, Encoding.UTF8), UrlEncode(PassWord, Encoding.UTF8)), true, out Str);//用之前获取页面的Cookie模拟用户授权
                #endregion
                string oauth_nonce = new Random().NextDouble().ToString().Substring(2, 13);
                oauth_nonce += oauth_nonce;
                string NowUnixTime = ConvertDateTimeInt(DateTime.Now).ToString();

                Dictionary<string, string> Argument = new Dictionary<string, string>();
                Argument.Add("oauth_nonce", oauth_nonce);
                Argument.Add("oauth_timestamp", NowUnixTime);
                Argument.Add("oauth_consumer_key", consumer_key);
                Argument.Add("oauth_token", Token);
                string Sign = OAuthSign("get", "https://openapi.kuaipan.cn/open/accessToken", Argument, consumer_secret + "&" + Token_Secret);

                string Url = string.Format("https://openapi.kuaipan.cn/open/accessToken?oauth_consumer_key={2}&oauth_timestamp={1}&oauth_nonce={0}&oauth_signature={3}&oauth_token={4}", oauth_nonce, NowUnixTime, consumer_key, Sign, Token);

                string ReturnData;
                GET_HTTP(Url, Url, "", "", false, new System.Net.CookieContainer(), true, out ReturnData);
                return JsonToDictionary.ToDictionary(ReturnData);
            }
            catch { return null; }

        }


        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="Method">数据传输方式（GET,POST）</param>
        /// <param name="Url">目标URL地址，不包括参数</param>
        /// <param name="Argument">参数</param>
        /// <param name="PassString">加密串</param>
        /// <returns></returns>
        static string OAuthSign(string Method, string Url, Dictionary<string, string> Argument,string PassString)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(Method.ToUpper());
            sb.Append("&" + UrlEncode(Url, Encoding.UTF8) + "&");

            ArrayList Ar = new ArrayList();
            foreach (var item in Argument.Keys)
            {
                Ar.Add(item);
            }
            Ar.Sort();

            foreach (var item in Ar)
            {
                sb.Append(UrlEncode(string.Format("&{0}={1}", item.ToString(), Argument[item.ToString()]), Encoding.UTF8));
            }
            string Sign = HmacSha1Sign(sb.ToString().Replace("&%26", "&"), PassString, Encoding.UTF8);
            return UrlEncode(Sign, Encoding.UTF8);
        }

        /// <summary>
        /// hmac-sha1算法
        /// </summary>
        /// <param name="text">源串</param>
        /// <param name="key">密串</param>
        /// <param name="encode">编码</param>
        /// <returns></returns>
        static string HmacSha1Sign(string text, string key, Encoding encode)
        {
            byte[] byteData = encode.GetBytes(text);
            byte[] byteKey = encode.GetBytes(key);
            HMACSHA1 hmac = new HMACSHA1(byteKey);
            CryptoStream cs = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);
            cs.Write(byteData, 0, byteData.Length);
            cs.Close();
            return Convert.ToBase64String(hmac.Hash);
        }














        public class CNNWebClient : WebClient
        {
            /// <summary>
            /// 重写GetWebRequest,添加WebRequest对象超时时间
            /// </summary>
            /// <param name="address"></param>
            /// <returns></returns>
            protected override WebRequest GetWebRequest(Uri address)
            {
                HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
                request.Timeout = 1000 * 3600;
                request.ReadWriteTimeout = 1000 * 3600;
                return request;
            }
        }


        #region 其他方法
        #region 获取指定网页源代码
        /// <summary>
        /// 获取指定网页源代码
        /// </summary>
        /// <param name="url">需要访问的URL</param>
        /// <param name="referer_post">来路</param>
        /// <param name="accept_post">返回数据格式,缺省值:*/*</param>
        /// <param name="useragent_post">浏览器头部标识符缺省值:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)</param>
        /// <param name="keepalive">编码格式  true=GB2312  false=UTF-8</param>
        /// <param name="CookieContainer_Post">请求页面的cookie</param>
        /// <param name="retError">是否返回错误消息</param>
        /// <param name="Msg">OUT返回的网页源代码</param>
        /// <returns></returns>
         static CookieContainer GET_HTTP(string url, string referer_post, string accept_post, string useragent_post, bool keepalive, CookieContainer CookieContainer_Post, bool retError, out string msg)
        {
            try
            {
                System.Uri httpposturl = new System.Uri(url);
                HttpWebRequest reqp;
                reqp = WebRequest.Create(url) as HttpWebRequest;
                reqp.Method = "GET";
                reqp.Referer = referer_post;
                //reqp.Timeout = 5000;
                if (accept_post == string.Empty) accept_post = "*/*";
                reqp.Accept = accept_post;
                if (useragent_post == string.Empty) useragent_post = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
                reqp.UserAgent = useragent_post;
                //reqp.Headers.Add("Host", "pan.baidu.com");
                //reqp.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
                //reqp.Headers.Add("Connection", "keep-alive");
                //reqp.Headers.Add("cookie", CookieContainer_Post);

                //reqp.Headers.Add("cookie", CookieContainer_Post);
                reqp.CookieContainer = CookieContainer_Post;
                reqp.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Anonymous;
                HttpWebResponse resp = reqp.GetResponse() as HttpWebResponse;
                if (keepalive == true)
                {
                    StreamReader reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.Default);
                    string respHTML = reader.ReadToEnd();
                    //string cookies = "";
                    //foreach (var s in resp.Cookies)
                    //{
                    //    cookies += s ;
                    //}
                    //Form1.caozuo.Cookies = cookies;
                    //Form1.caozuo.User_Cookies = reqp.CookieContainer;
                    resp.Close();
                    msg = respHTML;
                    return reqp.CookieContainer;
                }
                else
                {
                    StreamReader reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8);
                    string respHTML = reader.ReadToEnd();
                    //string cookies = "";
                    //foreach (var s in resp.Cookies)
                    //{
                    //    cookies += s ;
                    //}
                    //Form1.caozuo.Cookies = cookies;
                    //Form1.caozuo.User_Cookies = reqp.CookieContainer;
                    resp.Close();
                    msg = respHTML;
                    return reqp.CookieContainer;
                }

            }
            catch (Exception ee)
            {
                string str = ee.Message.ToString();
                if (retError)
                {
                    msg = @"{""Code"":-999,""Msg"":""" + str + @"""}";
                    //msg = "Error(错误)::" + str;
                    return null;
                }
                else
                {
                    msg = "";
                    return null;
                }
            }
        }//获取网页源代码

         static string GET_HTTP(string url, string referer_post, string accept_post, string useragent_post, bool keepalive, CookieContainer CookieContainer_Post, bool retError)
        {
            try
            {
                System.Uri httpposturl = new System.Uri(url);
                HttpWebRequest reqp;
                reqp = WebRequest.Create(url) as HttpWebRequest;
                reqp.Method = "GET";
                reqp.Referer = referer_post;
                reqp.Timeout = 5000;
                if (accept_post == string.Empty) accept_post = "*/*";
                reqp.Accept = accept_post;
                if (useragent_post == string.Empty) useragent_post = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
                reqp.UserAgent = useragent_post;
                reqp.CookieContainer = CookieContainer_Post;
                HttpWebResponse resp = reqp.GetResponse() as HttpWebResponse;
                if (keepalive == true)
                {
                    StreamReader reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.Default);
                    string respHTML = reader.ReadToEnd();
                    string cookies = "";
                    foreach (var s in resp.Cookies)
                    {
                        cookies += s;
                    }
                    //Form1.caozuo.Cookies = cookies;
                    //Form1.caozuo.User_Cookies = reqp.CookieContainer;
                    resp.Close();
                    return respHTML;
                }
                else
                {
                    StreamReader reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8);
                    string respHTML = reader.ReadToEnd();
                    string cookies = "";
                    foreach (var s in resp.Cookies)
                    {
                        cookies += s;
                    }
                    //Form1.caozuo.Cookies = cookies;
                    //Form1.caozuo.User_Cookies = reqp.CookieContainer;
                    resp.Close();
                    return respHTML;
                }

            }
            catch (Exception ee)
            {
                string str = ee.Message.ToString();
                if (retError)
                {
                    return str;
                }
                else
                {
                    return "";
                }
            }
        }//获取网页源代码


         static string GET_HTTP(string url, string referer_post, string accept_post, string useragent_post, bool keepalive, CookieContainer CookieContainer_Post, string code, bool retError)
        {
            try
            {
                System.Uri httpposturl = new System.Uri(url);

                HttpWebRequest reqp;
                reqp = WebRequest.Create(url) as HttpWebRequest;
                reqp.Method = "GET";
                reqp.Referer = referer_post;
                if (accept_post == string.Empty) accept_post = "*/*";
                reqp.Accept = accept_post;
                if (useragent_post == string.Empty) useragent_post = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
                reqp.UserAgent = useragent_post;
                reqp.Headers.Add("Authorization", "Basic " + code);
                reqp.CookieContainer = CookieContainer_Post;
                HttpWebResponse resp = reqp.GetResponse() as HttpWebResponse;
                if (keepalive == true)
                {
                    StreamReader reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.Default);
                    string respHTML = reader.ReadToEnd();
                    resp.Close();
                    return respHTML;
                }
                else
                {
                    StreamReader reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8);
                    string respHTML = reader.ReadToEnd();
                    resp.Close();
                    return respHTML;
                }

            }
            catch (Exception ee)
            {
                string str = ee.Message.ToString();
                if (retError)
                {
                    return str;
                }
                else
                {
                    return "";
                }
            }
        }
         static string GET_HTTP(string url, string referer_post, string accept_post, string useragent_post, bool keepalive, CookieContainer CookieContainer_Post, Int32 time, bool retError)
        {
            try
            {
                System.Uri httpposturl = new System.Uri(url);
                HttpWebRequest reqp;
                reqp = WebRequest.Create(url) as HttpWebRequest;
                reqp.Method = "GET";
                reqp.Referer = referer_post;
                if (accept_post == string.Empty) accept_post = "*/*";
                reqp.Accept = accept_post;
                if (useragent_post == string.Empty) useragent_post = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
                reqp.UserAgent = useragent_post;
                reqp.CookieContainer = CookieContainer_Post;
                reqp.Timeout = time;
                HttpWebResponse resp = reqp.GetResponse() as HttpWebResponse;
                if (keepalive == true)
                {
                    StreamReader reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.Default);
                    string respHTML = reader.ReadToEnd();
                    resp.Close();
                    return respHTML;
                }
                else
                {
                    StreamReader reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
                    string respHTML = reader.ReadToEnd();
                    resp.Close();
                    return respHTML;
                }

            }
            catch (Exception ee)
            {
                string str = ee.Message.ToString();
                if (retError)
                {
                    return str;
                }
                else
                {
                    return "";
                }
            }
        }
        #endregion
        #region Post发送数据包

        private static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受   
        }
        /// <summary>
        /// 发送数据包,并且返回Cookies到Form1中的User_Cookies;
        /// </summary>
        /// <param name="URL_Post">POST请求的页面地址是什么？</param>
        /// <param name="Referer_Post">请求来路是什么？</param>
        /// <param name="Accept_Post">返回的数据格式是什么?缺省值:*/*</param>
        /// <param name="UserAgent_Post">请求的浏览器头部是什么？缺省值:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)</param>
        /// <param name="KeepAlive_Post">是否保持在线状态?</param>
        /// <param name="encoding">请求的格式是什么？true=GB2312,false=UTF-8</param>
        /// <param name="CookieContainer_Post">cookies是哪个？</param>
        /// <param name="Post_Data_String">POST发送的数据是什么？</param>
        /// /// <param name="retError">是否显示错误提示(Flase的话错误的时候返回空值)</param>
        /// <param name="Msg">返回的网页源代码</param>
        /// <returns></returns>
         static CookieContainer POST_SITE_DATA_Cookie(string URL_Post, string Referer_Post, string Accept_Post, string UserAgent_Post, bool KeepAlive_Post, bool encoding, CookieContainer CookieContainer_Post, string Post_Data_String, bool retError, out string msg)
        {
            try
            {
                Uri httpUrl = new Uri(URL_Post);
                HttpWebRequest req = null;
                if (URL_Post.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    req = ((HttpWebRequest)(WebRequest.Create(httpUrl)));
                    req.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    req = ((HttpWebRequest)(WebRequest.Create(httpUrl)));
                }

                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Referer = Referer_Post;
                if (Accept_Post == string.Empty) Accept_Post = "*/*";
                req.Accept = Accept_Post;
                if (UserAgent_Post == string.Empty) UserAgent_Post = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
                req.UserAgent = UserAgent_Post;
                req.KeepAlive = KeepAlive_Post;
                req.CookieContainer = CookieContainer_Post;
                if (encoding)
                {
                    byte[] bytesData = System.Text.Encoding.Default.GetBytes(Post_Data_String);

                    req.ContentLength = bytesData.Length;
                    using (Stream postStream = req.GetRequestStream())
                    {
                        postStream.Write(bytesData, 0, bytesData.Length);
                    }
                    HttpWebResponse res = ((HttpWebResponse)(req.GetResponse()));
                    using (StreamReader reader = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default))
                    {
                        string respHTML = reader.ReadToEnd();
                        res.Close();
                        msg = respHTML;
                        return req.CookieContainer;
                    }
                }
                else
                {
                    byte[] bytesData = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(Post_Data_String);
                    req.ContentLength = bytesData.Length;
                    using (Stream postStream = req.GetRequestStream())
                    {
                        postStream.Write(bytesData, 0, bytesData.Length);
                    }
                    HttpWebResponse res = ((HttpWebResponse)(req.GetResponse()));
                    using (StreamReader reader = new StreamReader(res.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")))
                    {
                        string respHTML = reader.ReadToEnd();
                        res.Close();
                        msg = respHTML;
                        return req.CookieContainer;
                    }
                }
            }
            catch (Exception ee)
            {
                string str = ee.Message.ToString();
                if (retError)
                {
                    msg = @"{""Code"":-999,""Msg"":""" + str + @"""}";
                    return null;
                }
                else
                {
                    msg = "";
                    return null;
                }
            }
        }

        /// <summary>
        /// 发送数据包,并且返回Cookies到Form1中的User_Cookies;
        /// </summary>
        /// <param name="URL_Post">POST请求的页面地址是什么？</param>
        /// <param name="Referer_Post">请求来路是什么？</param>
        /// <param name="Accept_Post">返回的数据格式是什么?缺省值:*/*</param>
        /// <param name="UserAgent_Post">请求的浏览器头部是什么？缺省值:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)</param>
        /// <param name="KeepAlive_Post">是否保持在线状态?</param>
        /// <param name="encoding">请求的格式是什么？true=GB2312,false=UTF-8</param>
        /// <param name="CookieContainer_Post">cookies是哪个？</param>
        /// <param name="Post_Data_String">POST发送的数据是什么？</param>
        /// <param name="retError">是否显示错误提示(Flase的话错误的时候返回空值)</param>
        /// <param name="Msg">返回的网页源代码</param>
        /// <param name="cookie">返回的文本类cookie</param>
        /// <returns></returns>
         static CookieContainer POST_SITE_DATA_Cookie(string URL_Post, string Referer_Post, string Accept_Post, string UserAgent_Post, bool KeepAlive_Post, bool encoding, string CookieContainer_Post, string Post_Data_String, bool retError, out string msg, out string cookie)
        {
            try
            {
                Uri httpUrl = new Uri(URL_Post);
                HttpWebRequest req = null;
                if (URL_Post.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    req = ((HttpWebRequest)(WebRequest.Create(httpUrl)));
                    req.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    req = ((HttpWebRequest)(WebRequest.Create(httpUrl)));
                }

                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Referer = Referer_Post;
                req.Headers.Add("Cookie", CookieContainer_Post);
                if (Accept_Post == string.Empty) Accept_Post = "*/*";
                req.Accept = Accept_Post;
                if (UserAgent_Post == string.Empty) UserAgent_Post = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
                req.UserAgent = UserAgent_Post;
                req.KeepAlive = KeepAlive_Post;
                //req.AuthenticationLevel = "";
                //req.CookieContainer = CookieContainer_Post;
                if (encoding)
                {
                    byte[] bytesData = System.Text.Encoding.Default.GetBytes(Post_Data_String);

                    req.ContentLength = bytesData.Length;
                    using (Stream postStream = req.GetRequestStream())
                    {
                        postStream.Write(bytesData, 0, bytesData.Length);
                    }
                    HttpWebResponse res = ((HttpWebResponse)(req.GetResponse()));
                    using (StreamReader reader = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default))
                    {
                        string cookies = "";
                        string respHTML = reader.ReadToEnd();
                        foreach (var item in res.Cookies)
                        {
                            cookies += item + ";";
                        }
                        cookie = cookies;
                        res.Close();
                        msg = respHTML;
                        return req.CookieContainer;
                    }
                }
                else
                {
                    byte[] bytesData = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(Post_Data_String);
                    req.ContentLength = bytesData.Length;
                    using (Stream postStream = req.GetRequestStream())
                    {
                        postStream.Write(bytesData, 0, bytesData.Length);
                    }
                    HttpWebResponse res = ((HttpWebResponse)(req.GetResponse()));
                    using (StreamReader reader = new StreamReader(res.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")))
                    {
                        string cookies = "";
                        string respHTML = reader.ReadToEnd();
                        foreach (var item in res.Cookies)
                        {
                            cookies += item + ";";
                        }
                        cookie = cookies;
                        res.Close();
                        msg = respHTML;
                        return req.CookieContainer;
                    }
                }
            }
            catch (Exception ee)
            {
                string str = ee.Message.ToString();
                if (retError)
                {
                    msg = "Error(错误)::" + str;
                    cookie = "";
                    return null;
                }
                else
                {
                    msg = "";
                    cookie = "";
                    return null;
                }
            }
        }

        #endregion
        #region 获取指定字符串
        /// <summary>
        /// 获取字符串中指定的数据
        /// </summary>
        /// <param name="shuju">你要从哪个字符串中获取数据呢?</param>
        /// <param name="tou">要从哪个字符串开始获取呢？</param>
        /// <param name="wei">要获取到哪个字符串结束呢？</param>
        /// <param name="pd">获取的结果要包含用来判断开始和结束的字符串么？true=包含,false=不包含</param>
        /// <param name="weiyi">获取的结果是否要增加或者减少呢？减少5个就输入-5，增加5个就输入5，不增加不减少输入0就OK</param>
        /// <returns></returns>
         static string GetString(string shuju, string tou, string wei, bool pd, int weiyi)
        {
            //C#获取字符串中需要的部分。
            //作者:小C
            //使用时请保留此版权说明,谢谢！
            //使用说明:第一个参数:需要从某个文件、变量获取字符串;
            //第二个参数:需要获取的字符串开头;
            //第三个参数:需要获取的字符串结尾;
            //第四个参数:True=获取的字符串中包含字符串开头和结尾,False=获取的字符串中不包含开头和结尾;
            //第五个参数:多获取指定数量的字符.
            //------------=-------------奇怪的分割线------------=-------------
            try
            {
                if (tou == string.Empty) tou = "!!@xiaoC@!!@xiaoC@!!";
                if (wei == string.Empty) wei = "@xiaoC@!!@xiaoC@!!@xiaoC@";
                shuju = "!!@xiaoC@!!@xiaoC@!!" + shuju + "@xiaoC@!!@xiaoC@!!@xiaoC@";
                string linshi = "";
                if (pd == true)
                {
                    string kaishi;
                    kaishi = shuju.Substring(shuju.IndexOf(tou), shuju.Length - shuju.IndexOf(tou));
                    linshi = kaishi.Substring(0, kaishi.IndexOf(wei) + weiyi + wei.Length);
                }
                else
                {
                    string kaishi;
                    kaishi = shuju.Substring(shuju.IndexOf(tou), shuju.Length - shuju.IndexOf(tou));
                    linshi = kaishi.Substring(0, kaishi.IndexOf(wei) + weiyi + wei.Length);
                    if (tou.Length >= wei.Length)
                    {
                        linshi = (linshi.Replace(tou, "").Replace(wei, "")).Trim();
                    }
                    else
                    {
                        linshi = (linshi.Replace(wei, "").Replace(tou, "")).Trim();
                    }
                }
                string str = linshi.Replace("@xiaoC@!!@xiaoC@!!@xiaoC@", "").Replace("!!@xiaoC@!!@xiaoC@!!", "");
                return str;
            }
            catch (Exception ee)
            {
                return "";
            }
        }//获取指定字符串
         static string GetString(string shuju, string tou)
        {
            //C#获取字符串中需要的部分。
            //作者:小C
            //使用时请保留此版权说明,谢谢！
            //使用说明:第一个参数:需要从某个文件、变量获取字符串;
            //第二个参数:需要获取的字符串开头;
            //第三个参数:需要获取的字符串结尾;
            //第四个参数:True=获取的字符串中包含字符串开头和结尾,False=获取的字符串中不包含开头和结尾;
            //第五个参数:多获取指定数量的字符.
            //------------=-------------奇怪的分割线------------=-------------
            try
            {
                tou += "[";
                string wei = "]";
                string linshi = "";
                string kaishi;
                kaishi = shuju.Substring(shuju.IndexOf(tou), shuju.Length - shuju.IndexOf(tou));
                linshi = kaishi.Substring(0, kaishi.IndexOf(wei) + wei.Length);
                if (tou.Length >= wei.Length)
                {
                    linshi = (linshi.Replace(tou, "").Replace(wei, "")).Trim();
                }
                else
                {
                    linshi = (linshi.Replace(wei, "").Replace(tou, "")).Trim();
                }
                return linshi;
            }
            catch (Exception ee)
            {
                return "";
            }
        }//快速获取

         static string GetLastString(string shuju, string tou, string wei, bool pd, int weiyi)
        {
            //C#获取字符串中最后一个需要的部分。
            //作者:小C
            //使用时请保留此版权说明,谢谢！
            //使用说明:第一个参数:需要从某个文件、变量获取字符串;
            //第二个参数:需要获取的字符串开头;
            //第三个参数:需要获取的字符串结尾;
            //第四个参数:True=获取的字符串中包含字符串开头和结尾,False=获取的字符串中不包含开头和结尾;
            //第五个参数:多获取指定数量的字符.
            //------------=-------------奇怪的分割线------------=-------------
            try
            {
                if (tou == string.Empty) tou = "!!@xiaoC@!!@xiaoC@!!";
                if (wei == string.Empty) wei = "@xiaoC@!!@xiaoC@!!@xiaoC@";
                shuju = "!!@xiaoC@!!@xiaoC@!!" + shuju + "@xiaoC@!!@xiaoC@!!@xiaoC@";
                string linshi = "";
                if (pd == true)
                {
                    string kaishi;
                    kaishi = shuju.Substring(shuju.LastIndexOf(tou), shuju.Length - shuju.LastIndexOf(tou));
                    linshi = kaishi.Substring(0, kaishi.IndexOf(wei) + weiyi + wei.Length);
                }
                else
                {
                    string kaishi;
                    kaishi = shuju.Substring(shuju.LastIndexOf(tou), shuju.Length - shuju.LastIndexOf(tou));
                    linshi = kaishi.Substring(0, kaishi.IndexOf(wei) + weiyi + wei.Length);
                    if (tou.Length >= wei.Length)
                    {
                        linshi = (linshi.Replace(tou, "").Replace(wei, "")).Trim();
                    }
                    else
                    {
                        linshi = (linshi.Replace(wei, "").Replace(tou, "")).Trim();
                    }
                }
                return linshi.Replace("@xiaoC@!!@xiaoC@!!@xiaoC@", "").Replace("!!@xiaoC@!!@xiaoC@!!", "");
                //return linshi;
            }
            catch
            {
                return ("");
            }
        }//获取指定字符串
        #endregion
         #region DateTime时间格式转换为Unix时间戳格式
         /// <summary>
         /// DateTime时间格式转换为Unix时间戳格式
         /// </summary>
         /// <param name=”time”></param>
         /// <returns></returns>
         static int ConvertDateTimeInt(System.DateTime time)
         {
             System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
             return (int)(time - startTime).TotalSeconds;
         }
         #endregion
        #endregion

        #region 大写的URL编码
        private static string UrlEncode(string temp, Encoding encoding)
        {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < temp.Length; i++)
            {
                string t = temp[i].ToString();
                string k = System.Web.HttpUtility.UrlEncode(t, encoding);
                if (t == k)
                {
                    stringBuilder.Append(t);
                }
                else
                {
                    stringBuilder.Append(k.ToUpper());
                }
            }
            return stringBuilder.ToString();
        }
        #endregion

        #region JSON转换
        public static class JsonToDictionary
        {
            /// <summary>
            /// Json格式转换成键值对，键值对中的Key需要区分大小写
            /// </summary>
            /// <param name="JsonData">需要转换的Json文本数据</param>
            /// <returns></returns>
            public static Dictionary<string, object> ToDictionary(string JsonData)
            {
                object Data = null;
                Dictionary<string, object> Dic = new Dictionary<string, object>();
                if (JsonData.StartsWith("["))
                {
                    //如果目标直接就为数组类型，则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
                    //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
                    List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
                    MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
                    foreach (Match ListItem in ListMatch)
                    {
                        List.Add(ToDictionary(ListItem.ToString()));//递归调用
                    }
                    Data = List;
                    Dic.Add("List", Data);
                }
                else
                {
                    MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|true|false|"".*?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
                    foreach (Match item in Match)
                    {
                        try
                        {
                            if (item.Groups[2].ToString().StartsWith("["))
                            {
                                //如果目标是数组，将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
                                //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
                                List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
                                MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
                                foreach (Match ListItem in ListMatch)
                                {
                                    List.Add(ToDictionary(ListItem.ToString()));//递归调用
                                }
                                Data = List;
                            }
                            else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
                            else if (item.Groups[2].ToString() == "\"\"") Data = "";
                            else
                            {
                                if (item.Groups[2].ToString() == "true") Data = true;
                                else if (item.Groups[2].ToString() == "false") Data = false;
                                else
                                {
                                    Data = ToGB2312(item.Groups[2].ToString());
                                    if (Data.ToString().StartsWith("\""))
                                    {
                                        Data = Data.ToString().Substring(1, Data.ToString().Length - 1);
                                    }
                                    if (Data.ToString().EndsWith("\""))
                                    {
                                        Data = Data.ToString().Substring(0, Data.ToString().Length - 1);
                                    }
                                }
                            }
                            Dic.Add(item.Groups[1].ToString(), Data);
                        }
                        catch { }
                    }
                }
                return Dic;
            }

            #region 将Unicode编码转换为汉字字符串
            /// <summary>
            /// 将Unicode编码转换为汉字字符串
            /// </summary>
            /// <param name="str">Unicode编码字符串</param>
            /// <returns>汉字字符串</returns>
            static string ToGB2312(string str)
            {
                MatchCollection mc = Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                byte[] bts = new byte[2];
                foreach (Match m in mc)
                {
                    bts[0] = (byte)int.Parse(m.Groups[2].Value, System.Globalization.NumberStyles.HexNumber);
                    bts[1] = (byte)int.Parse(m.Groups[1].Value, System.Globalization.NumberStyles.HexNumber);
                    str = str.Replace(m.ToString(), Encoding.Unicode.GetString(bts));
                }
                return str;
            }
            #endregion
        }
        #endregion
    }
}
